package com.gpj.netty.demo.bio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * @className BIOSocketServer
 * @description
 *   BIO通信模式的服务端代码
 * @author GPJ
 * @date 2021/1/29 22:53
 * @version 1.0
 **/
@Slf4j
public class BIOSocketServer {
	public static void main(String[] args) throws IOException {
		ServerSocket serverSocket = new ServerSocket(9999);
		while (true){
			log.info("等待客户端连接...");
			Socket socket = serverSocket.accept();
			log.info("收到客户端请求,正在进行处理...");
			new Thread(() -> {
					handle(socket);
			}).start();
		}
	}
	
	public static void handle(Socket clientSocket){
	    byte[] datas = new byte[1024];
		try {
			int num = clientSocket.getInputStream().read(datas);
			if(num != -1){
				log.info("接收到客户端发来的数据:[{}]", new String(datas, 0, num, StandardCharsets.UTF_8));
			}
			clientSocket.getOutputStream().write("请求已收到".getBytes());
			clientSocket.getOutputStream().flush();
		} catch (IOException e) {
			log.error("客户端请求处理失败:{}", e.getMessage(), e);
		}
	}
}
